package ${initProjectVo.packageNameValue}.core.filter;

import ${initProjectVo.packageNameValue}.core.wrapper.HeaderHttpServletRequestWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class SessionFilter implements Filter {
public List<String> excludes = new ArrayList<String>();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {


        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        if(handleExcludeURL(req, resp)){
            filterChain.doFilter(request, response);
            return;
        }
        HeaderHttpServletRequestWrapper httpServletRequestWrapper=new HeaderHttpServletRequestWrapper((HttpServletRequest) request);
        filterChain.doFilter(httpServletRequestWrapper,response);
    }

    private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) {

        if (excludes == null || excludes.isEmpty()) {
            return false;
        }

        String url = request.getServletPath();
        for (String pattern : excludes) {
            Pattern p = Pattern.compile("^" + pattern);
            Matcher m = p.matcher(url);
            if (m.find()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String ignoreUrl =  filterConfig.getInitParameter("excludes");
        if(!StringUtils.isEmpty(ignoreUrl)){
            String[] urls = ignoreUrl.split(",");
            for(String url : urls){
                excludes.add(url);
            }
        }
    }
}
